import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This class will add post to the class.

public class AddPost extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
	response.setContentType("text/plain");
	
	PrintWriter pw = response.getWriter();
	String user_id = request.getParameter("userId");
	String course = request.getParameter("courseCode");
	String message = request.getParameter("msg");
	String lastUpdatedTime = request.getParameter("time");
	//if userId !="", add to database then update.
	
	//connect to the database
	Connection con = null;
	Statement stmt = null;
	ResultSet rs = null;
	PreparedStatement pst = null;
	
	//NOW() is will add the current timestamp
	String query = "INSERT INTO post (course,user_id, date, message) values (?,?,NOW(),?)";	
	try {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		con = DriverManager.getConnection("jdbc:mysql://bungle08.cs.toronto.edu:3306/group22",
			"group22", "123456");
		if(!con.isClosed()){
		
			// If user_id is empty, this is when the user has just added course and has not 
			// added a real post. So there will be no post to update the database.
			// However, if it is now, this means that the user has acutally post something and
			// we will update the database.
			if (user_id != ""){
					
				pst = con.prepareStatement(query);
				pst.setString(1,course);
				pst.setString(2,user_id);
				pst.setString(3,message);

				int i = pst.executeUpdate();
				if(i!=0){
									
				}			
			}
			
			// This will return to the application the information about the post for the course 
			// If lastUpdatedTime is null or "" that means, the user has just added this course. So
			// We will return all the posts in the database for that course
		//	if (lastUpdatedTime == null || lastUpdatedTime == ""){
				query = "SELECT * FROM post where course = \""+course+"\" order by date";
				
		//	} else{
			// If not, we will return the post that has been added after the last update.
			// This will help becuase, we do not have to refresh all of the post every time the user
			// accesses the course.
		//		query = "SELECT * FROM post where date > \"" + lastUpdatedTime + "\" &&  course = \""+course+"\" order by date";
			
		//	}
						
			

			stmt = con.createStatement();		
			rs = stmt.executeQuery(query);			
			// Return information about the post back to the application		
			while (rs.next()) {
				pw.println(rs.getString("user_id"));
				pw.println(rs.getString("date").substring(0,rs.getString("date").length()-2));
				pw.println(rs.getString("message"));
				pw.println(rs.getString("id"));
					
			}
			
		}
	}
	 catch(Exception e) {
		pw.println("Exception: " + e.getMessage());
	} finally {
		try {
			if(con != null)
				con.close();
		} catch(SQLException e) {}
	}}
}
	